package com.csthink.mq.rocketmq.enhance;

import org.apache.rocketmq.spring.support.DefaultRocketMQListenerContainer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.StringUtils;

/**
 * 增强型 {@link RocketMQEnhanceAutoConfiguration} 的环境隔离配置后置处理类
 * @author <a href="mailto:security.2009@live.cn">Mars</a>
 * @since 2023-09-07
 */
public class EnvironmentIsolationConfig implements BeanPostProcessor {
    private final RocketEnhanceProperties rocketEnhanceProperties;

    public EnvironmentIsolationConfig(RocketEnhanceProperties rocketEnhanceProperties) {
        this.rocketEnhanceProperties = rocketEnhanceProperties;
    }


    /**
     * 在装载Bean之前实现参数修改
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof DefaultRocketMQListenerContainer) {

            DefaultRocketMQListenerContainer container = (DefaultRocketMQListenerContainer) bean;

            if (rocketEnhanceProperties.isEnabledIsolation() && StringUtils.hasText(rocketEnhanceProperties.getEnvironment())) {
                container.setTopic(String.join("_", container.getTopic(), rocketEnhanceProperties.getEnvironment()));
            }
            return container;
        }
        return bean;
    }
}

